package com.sx.baseproject.framework.adapter.binding.adapter;


import android.util.Log;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;

import com.sx.baseproject.framework.adapter.binding.bean.FragmentTitleArgument;

import java.util.ArrayList;
import java.util.List;

/**
 * @author :create by lhw
 * time :{DATE} {HOUR}
 * email :785661432@qq.com
 * phone :13018600506
 * 内容:
 */
public class MyViewPagerAdapter extends FragmentStatePagerAdapter {
    private List<Fragment> fragments = new ArrayList<>();
    private List<String> titles = new ArrayList<>();
    private boolean isPageTitle = true;

    public void setFragments(List<Fragment> fragments) {
        this.fragments = fragments;
    }

    public List<Fragment> getFragments() {
        return fragments;
    }

    public MyViewPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    public MyViewPagerAdapter(FragmentManager fm, List<Fragment> fragments, List<String> fragmentTitle) {
        super(fm);
        this.fragments = fragments;
        this.titles = fragmentTitle;
    }

    public MyViewPagerAdapter(FragmentManager fm, List<FragmentTitleArgument> fragments) {
        super(fm);
        for (FragmentTitleArgument fragment : fragments) {
            this.fragments.add(fragment.getFragment());
            this.titles.add(fragment.getTitle());
        }
    }
    public void setPageTitle(boolean pageTitle) {
        isPageTitle = pageTitle;
    }


    @Override
    public CharSequence getPageTitle(int position) {
        if (isPageTitle)
            return titles.size() > position ? titles.get(position) : super.getPageTitle(position);
        else
            return super.getPageTitle(position);
    }

    public void addFragment(Fragment fragment, String title) {
        if (fragment != null) {
            fragments.add(fragment);
        }
        if (title != null) {
            titles.add(title);
        }
    }

    public void addFragment(Fragment fragment) {
        addFragment(fragment, null);
    }

    @Override
    public Fragment getItem(int i) {
        return fragments.get(i);
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        super.destroyItem(container, position, object);
        Log.i("MyViewPagerAdapter", "destroyItem: " + position);
    }

    @Override
    public void setPrimaryItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        super.setPrimaryItem(container, position, object);
        Log.i("MyViewPagerAdapter", "setPrimaryItem: " + position);
    }

    @Override
    public int getCount() {
        return fragments.size();
    }
}
